package pl.enigmatic.util;

import java.util.Collection;
import java.util.Iterator;

import pl.enigmatic.math.MathUtil;


// FIXME - te funkcje trzeba sprawdzić, bo będą sprawiać problemy
public class Collections {

	private Collections() {}

	public static int clamp(final Collection<?> collection, final int index) {
		return MathUtil.clamp(0, collection.size(), index);
	}

	public static int wrap(final Collection<?> collection, final int index) {
		return MathUtil.wrap(0, collection.size(), index);
	}

	public static <T> T[] toArray(final Collection<T> col, final T[] array) {
		int i = 0;
		for (final T t : col) {
			array[i++] = t;
		}
		return array;
	}

	public static <T> Iterator<T> iterator(final Iterable<? extends T>... iterables) {
		return new Iterator<T>() {

			private int next = 0;
			private Iterator<? extends T> current;

			{
				countNext();
				if (next < iterables.length) {
					current = iterables[next++].iterator();
					countNext();
				}
			}

			private void countNext() {
				while (next < iterables.length && !iterables[next].iterator().hasNext()) {
					next++;
				}
			}

			public boolean hasNext() {
				if (current == null) {
					return false;
				}
				if (!current.hasNext()) {
					countNext();
					return next < iterables.length;
				}
				return true;
			}

			public T next() {
				if (!current.hasNext()) {
					current = iterables[next++].iterator();
					countNext();
				}
				return current.next();
			}

			public void remove() {
				current.remove();
			}
		};
	}

	public static <T> Iterable<T> iterable(final Iterable<? extends T>... iterables) {
		return new Iterable<T>() {

			public Iterator<T> iterator() {
				return Collections.iterator(iterables);
			}
		};
	}

}
